package com.yun.aspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;

@Component
@Aspect
public class LogConfig {

    private final static Logger logger = LoggerFactory.getLogger(LogConfig.class);

    @Pointcut("execution(public * com.yun.controller.*.*(..))")
    public void execute() {
    }

    @Before(value = "execute()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info(
                "****************************************************************************************************************************************************************************");

        logger.info("请求接口={}", request.getRequestURL());

        logger.info("请求方法={}",
                joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        String param = "";
        if (joinPoint.getArgs().length > 0) {
            for (Object o : joinPoint.getArgs()) {
                if (o instanceof HttpServletRequest || o instanceof HttpServletResponse) {
                    continue;
                }
                param = new Gson().toJson(o);
            }
        }
        logger.info("请求参数-json={}", param);
        
        logger.info("请求地址={}", request.getRemoteAddr());

        logger.info("请求方式={}", request.getMethod());
    }
    
    @AfterReturning(value = "execute()", returning = "value")
    public void after(Object value) {
        logger.info("响应参数={}", new Gson().toJson(value));
    }

}
